# ai_content_generator.py
import os
import requests
import json
import logging

class AIContentGenerator:
    def __init__(self, api_key=None, model_name="Qwen/Qwen3-8B"):
        """初始化AI内容生成器

        Args:
            api_key (str, optional): 硅基流动平台的API密钥. Defaults to None.
            model_name (str, optional): 使用的AI模型名称. Defaults to "Qwen/Qwen3-8B".
        """
        self.api_key = api_key or os.getenv('SILICONFLOW_API_KEY')
        if not self.api_key:
            raise ValueError('请提供API密钥或设置SILICONFLOW_API_KEY环境变量')
        self.model_name = model_name
        self.api_url = "https://api.siliconflow.cn/v1/chat/completions"
        print(f"AI内容生成器已初始化，使用模型: {self.model_name}")

    def generate_content(self, prompt_text):
        """根据提示词生成内容

        Args:
            prompt_text (str): 用于生成内容的提示词.

        Returns:
            str: AI生成的文本内容.
        """
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        payload = {
            "model": self.model_name,
            "messages": [
                {"role": "system", "content": "你是一个专业的AI助手"},
                {"role": "user", "content": prompt_text}
            ],
            "temperature": 0.7,
            "top_p": 0.9,
            "max_tokens": 4000
        }

        try:
            response = requests.post(self.api_url, headers=headers, data=json.dumps(payload))
            response.raise_for_status()
            result = response.json()
            return result['choices'][0]['message']['content']
        except requests.exceptions.RequestException as e:
            logging.error(f"API请求失败: {e}")
            return f"[AI生成失败]：无法获取AI生成内容，请检查API配置。错误: {str(e)}"

if __name__ == '__main__':
    # 测试代码
    generator = AIContentGenerator()

    prompts_to_test = [
        "请描述项目的背景信息",
        "请阐述技术解决方案",
        "我们的商业模式是什么",
        "介绍一下核心团队成员"
    ]

    for p in prompts_to_test:
        generated_text = generator.generate_content(p)
        print(f"提示: {p}")
        print(f"生成: {generated_text}\n")